import { computed, ComputedRef, ref, unref } from 'vue';

import { sizeEnum, screenEnum, screenMap } from '/@/enums/breakpointEnum';

import { useEventListener } from '/@/hooks/event/useEventListener';

let globalScreenRef: ComputedRef<sizeEnum | undefined>;
let globalWidthRef: ComputedRef<number>;
let globelRealWidthRef: ComputedRef<number>;

export interface CreateCallBackParams {
  screen: ComputedRef<sizeEnum | undefined>;
  width: ComputedRef<number>;
  realWidth: ComputedRef<number>;
  screenEnum: typeof screenEnum;
  screenMap: Map<sizeEnum, number>;
  sizeEnum: typeof sizeEnum;
}

/**
 * @description: 创建屏幕宽度监听器触发一次
 */
export function createBreakpointLisenOnce(fn?: (opt: CreateCallBackParams) => void) {
  const screenRef = ref<sizeEnum>(sizeEnum.XL);
  const realWidthRef = ref(window.innerWidth);

  function getWindowWidth() {
    const width = document.body.clientWidth;
    const xs = screenMap.get(sizeEnum.XS)!;
    const sm = screenMap.get(sizeEnum.SM)!;
    const md = screenMap.get(sizeEnum.MD)!;
    const lg = screenMap.get(sizeEnum.LG)!;
    const xl = screenMap.get(sizeEnum.XL)!;
    if (width < xs) screenRef.value = sizeEnum.XS;
    else if (width < sm) screenRef.value = sizeEnum.SM;
    else if (width < md) screenRef.value = sizeEnum.MD;
    else if (width < lg) screenRef.value = sizeEnum.LG;
    else if (width < xl) screenRef.value = sizeEnum.XL;
    else screenRef.value = sizeEnum.XXL;

    realWidthRef.value = width;
  }

  getWindowWidth();
  globalScreenRef = computed(() => unref(screenRef));
  globalWidthRef = computed((): number => screenMap.get(unref(screenRef)!)!);
  globelRealWidthRef = computed(() => unref(realWidthRef));

  function resizeFn() {
    fn?.({
      screen: globalScreenRef,
      width: globalWidthRef,
      realWidth: globalWidthRef,
      screenEnum,
      screenMap,
      sizeEnum,
    });
  }

  resizeFn();

  useEventListener({
    el: window,
    name: 'resize',
    listener: () => {
      getWindowWidth();
      resizeFn();
    },
  });

  return {
    screenRef,
    screenEnum,
    widthRef: globalWidthRef,
    realWidth: globelRealWidthRef,
  };
}
